package com.yhq.thrift.client;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.transport.TTransport;

import java.lang.reflect.Method;

/**
 * Created by yhq on 2016/12/6.
 */
public class ThriftConnection {

    private final Object client;

    private final ServerKey serverKey;

    private final TTransport transport;

    private final ThriftGenericKeyedObjectPool<ServerKey, TTransport> pool;

    public ThriftConnection(Object client,ServerKey serverKey, TTransport transport) {
        this(client,serverKey, transport, null);
    }

    public ThriftConnection(Object client,ServerKey serverKey, TTransport transport, ThriftGenericKeyedObjectPool<ServerKey, TTransport> pool) {
        this.client = client;
        this.serverKey = serverKey;
        this.transport = transport;
        this.pool = pool;
    }

    public void close() {
        pool.returnObject(serverKey, transport);
    }

    public Object exec(Method method, Object[] params) throws Exception{
        if (!transport.isOpen()) {
            transport.open();
        }
        Object result = method.invoke(client, params);
        return result;
    }
}
